package com.cinemahorairerapido;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.format.DateFormat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.cinemahorairerapido.bean.Cinema;
import com.cinemahorairerapido.bean.Movie;
import com.cinemahorairerapido.controller.FavorisController;
import com.cinemahorairerapido.utils.DateUtils;
import com.viewpagerindicator.PageIndicator;
import com.viewpagerindicator.TabPageIndicator;

public class ShowTimeTabsFragment extends FragmentActivity {

	public static final String PARAM_CINEMA = "param_cinema";

	/**
	 * Base sample activity part
	 */

	private Cinema currentCinema;

	private FragmentPagerAdapter mAdapter;

	private ViewPager mPager;

	private PageIndicator mIndicator;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.simple_tabs);

		// block rotation
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

		Bundle extras = getIntent().getExtras();

		currentCinema = (Cinema) extras.getSerializable(ShowTimeTabsFragment.PARAM_CINEMA);
		final// Set theater name
		TextView theaterName = (TextView) findViewById(R.id.theatername);
		theaterName.setText(currentCinema.getName());

		// Set the action on checkbox
		CheckBox favoriteCheckBox = (CheckBox) findViewById(R.id.addfavorite);
		favoriteCheckBox.setChecked(FavorisController.getInstance(ShowTimeTabsFragment.this).isFavorite(currentCinema));

		favoriteCheckBox.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				final CheckBox cb = (CheckBox) v;

				if (!cb.isChecked()) {
					// when uncheck ask for confirmation
					AlertDialog.Builder builder = new AlertDialog.Builder(ShowTimeTabsFragment.this);
					builder.setMessage(getResources().getString(R.string.removeconfirmation)).setCancelable(false)
							.setPositiveButton(getResources().getString(R.string.yes), new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int id) {
									FavorisController.getInstance(ShowTimeTabsFragment.this).updateFavoris(currentCinema, cb.isChecked());
								}
							}).setNegativeButton(getResources().getString(R.string.no), new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int id) {
									cb.setChecked(true);
									dialog.cancel();
								}
							});
					AlertDialog alert = builder.create();
					alert.show();

				} else {
					FavorisController.getInstance(ShowTimeTabsFragment.this).updateFavoris(currentCinema, cb.isChecked());
				}
			}
		});

		// showDialog(1);

		// previous button
		ImageView previous = (ImageView) findViewById(R.id.previous);

		previous.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ShowTimeTabsFragment.this.finish();
			}
		});

		// init pager and indicator
		// mPager = (ViewPager) findViewById(R.id.pager);
		// mIndicator = (TabPageIndicator) findViewById(R.id.indicator);
		// mAdapter = new MovieShowTimeListAdapter(getSupportFragmentManager(),
		// initMoviesByDay(), this);
		// mPager.setAdapter(mAdapter);
		// mIndicator.setViewPager(mPager);
		//
		// progressdialog = ProgressDialog.show(ShowTimeTabsFragment.this, "",
		// getResources().getText(R.string.searching), true, true);
		//
		// FindShowTimesTask task = new FindShowTimesTask();
		// task.execute(currentCinema.getAllocineCode());

		// try {
		// movies =
		// AllocineController.getCinemaProgram(currentCinema.getAllocineCode());
		// } catch (IOException e) {
		// e.printStackTrace();
		// } catch (JSONException e) {
		// e.printStackTrace();
		// }
		initMovieList();

		// feedback nbtry before getting result
		// Dialog alert = AlertDialogBuilder.createAlertDialog(this, "Info",
		// "Nb Timeout :" + currentCinema.getNbTryBeforeGettingResult());
		// alert.show();
	}

	protected HashMap<Date, List<Movie>> initMoviesByDay() {

		// create an hashmap : day : movies
		HashMap<Date, List<Movie>> moviesByDay = new HashMap<Date, List<Movie>>();

		// add all the day until the next wesneday
		Calendar currentCal = new GregorianCalendar();
		currentCal.setTime(DateUtils.truncateHours(new Date()));

		// add the first day
		moviesByDay.put(currentCal.getTime(), new ArrayList<Movie>());
		currentCal.add(Calendar.DAY_OF_MONTH, 1);

		while (currentCal.get(Calendar.DAY_OF_WEEK) != Calendar.WEDNESDAY) {
			moviesByDay.put(currentCal.getTime(), new ArrayList<Movie>());
			currentCal.add(Calendar.DAY_OF_MONTH, 1);
		}

		return moviesByDay;
	}

	public void initMovieList() {

		HashMap<Date, List<Movie>> moviesByDay = initMoviesByDay();

		if (currentCinema.getProgram() != null) {
			for (Movie m : currentCinema.getProgram()) {

				for (Date d : m.getTimeList().keySet()) {

					if (!moviesByDay.containsKey(DateUtils.truncateHours(d))) {
						moviesByDay.put(DateUtils.truncateHours(d), new ArrayList<Movie>());
					}
					moviesByDay.get(DateUtils.truncateHours(d)).add(m);
				}
			}
		}

		mAdapter = new MovieShowTimeListAdapter(getSupportFragmentManager(), moviesByDay, this);

		mPager = (ViewPager) findViewById(R.id.pager);
		mPager.setAdapter(mAdapter);

		mIndicator = (TabPageIndicator) findViewById(R.id.indicator);
		mIndicator.setViewPager(mPager);

	}

	// private class FindShowTimesTask extends AsyncTask<String, Integer, Long>
	// {
	//
	// @Override
	// protected Long doInBackground(String... value) {
	//
	// try {
	//
	// movies = AllocineController.getCinemaProgram(value[0]);
	//
	// return new Long(1);
	//
	// } catch (IOException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// } catch (JSONException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// }
	//
	// return new Long(0);
	// }
	//
	// @Override
	// protected void onProgressUpdate(Integer... progress) {
	// // setProgressPercent(progress[0]);
	// }
	//
	// @Override
	// protected void onPostExecute(Long result) {
	//
	// // fill the list adapter
	// ShowTimeTabsFragment.this.initMovieList();
	//
	// // close progress dialog
	// if (progressdialog != null) {
	// progressdialog.cancel();
	// progressdialog = null;
	// }
	//
	// }
	// }

	public static class MovieShowTimeListAdapter extends FragmentPagerAdapter {

		private final HashMap<Date, List<Movie>> mMoviesByDay;

		private final List<Date> orderedDates;

		private final Context mContext;

		public MovieShowTimeListAdapter(FragmentManager fm, HashMap<Date, List<Movie>> moviesByDay, Context context) {
			super(fm);
			mContext = context;
			mMoviesByDay = moviesByDay;

			// get the keyset, ordered and put into the list
			orderedDates = new ArrayList<Date>(moviesByDay.keySet());

			Collections.sort(orderedDates);
		}

		@Override
		public Fragment getItem(int position) {
			Date date = orderedDates.get(position % orderedDates.size());
			return MovieShowTimeListFragment.newInstance(date, mMoviesByDay.get(date), mContext);

			// return
			// TestFragment.newInstance(ShowTimeTabsFragment.CONTENT[position %
			// ShowTimeTabsFragment.CONTENT.length]);
		}

		@Override
		public int getCount() {
			return orderedDates.size();

			// return ShowTimeTabsFragment.CONTENT.length;
		}

		@Override
		public CharSequence getPageTitle(int position) {

			return DateFormat.format("E dd MMM", orderedDates.get(position % orderedDates.size()));

			// return ShowTimeTabsFragment.CONTENT[position %
			// ShowTimeTabsFragment.CONTENT.length].toUpperCase();
		}

	}

	// @Override
	// public boolean onCreateOptionsMenu(Menu menu) {
	// getMenuInflater().inflate(R.menu.menu, menu);
	// return true;
	// }

	// @Override
	// public boolean onOptionsItemSelected(MenuItem item) {
	// switch (item.getItemId()) {
	// case R.id.random:
	// final int page = RANDOM.nextInt(mAdapter.getCount());
	// Toast.makeText(this, "Changing to page " + page, Toast.LENGTH_SHORT);
	// mPager.setCurrentItem(page);
	// return true;
	//
	// case R.id.add_page:
	// if (mAdapter.getCount() < 10) {
	// mAdapter.setCount(mAdapter.getCount() + 1);
	// mIndicator.notifyDataSetChanged();
	// }
	// return true;
	//
	// case R.id.remove_page:
	// if (mAdapter.getCount() > 1) {
	// mAdapter.setCount(mAdapter.getCount() - 1);
	// mIndicator.notifyDataSetChanged();
	// }
	// return true;
	// }
	// return super.onOptionsItemSelected(item);
	// }

}
